package kandl.automation.junit;


import org.apache.log4j.Logger;
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.model.InitializationError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import kandl.automation.testsuite.TestCase;
import kandl.automation.testsuite.TestProfile;
import kandl.automation.testsuite.TestSuite;
import kandl.automation.testsuite.TestSuiteFactory;
import static com.google.common.collect.Lists.newArrayList;

@Component
public class AutomationRunner {

    private static Logger logger = Logger.getLogger(AutomationRunner.class);

    @Autowired
    private TestSuiteFactory testSuiteFactory;

    @Autowired
    private ProfileRunner profileRunner;

    private List<TestSuite> testSuites;

    private DescriptionMapper dMapper;

    public AutomationRunner() {
        this.testSuites = newArrayList();
    }

    public AutomationRunner(TestSuiteFactory testSuiteFactory,
                            ProfileRunner profileRunner) throws InitializationError {
        this.testSuiteFactory = testSuiteFactory;
        this.profileRunner = profileRunner;
        this.testSuites = newArrayList();
    }

    public void setDescriptionMapper(DescriptionMapper mapper) {
        this.dMapper = mapper;
        this.profileRunner.setDescriptionMapper(mapper);
    }

    public TestSuite loadTestSuite(String name) throws InitializationError {

        try {
            TestSuite testSuite = testSuiteFactory.getSuiteForName(name);
            testSuites.add(testSuite);
            return testSuite;
        }
        catch (InitializationError e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        catch (Throwable e) {
            e.printStackTrace();
            logger.error("Cannot load test suite: " + name, e);
            throw new InitializationError(e);
        }
    }

    public void runAll(RunNotifier runNotifier, Description rootDescription) {

        for (TestSuite testSuite : getTestSuites()) {
            Description suiteDescription = dMapper.getDescription(testSuite.getName(), rootDescription);
            runSuite(testSuite, runNotifier, suiteDescription);
        }
    }
    
    private void runSuite(TestSuite testSuite, RunNotifier runNotifier, Description suiteDescription) {
        List<Future<Void>> activeRuns = newArrayList();
        
        for (TestProfile profile : testSuite.getProfiles()) {
            Description profileDescription = dMapper.getDescription(profile.getId(), suiteDescription);
            if (profile.isEnabled()) {
                Future<Void> future = profileRunner.runProfile(profile, testSuite, runNotifier, profileDescription);
                activeRuns.add(future);
            }
            else {
                profileRunner.ignoreProfile(profile, testSuite, runNotifier, profileDescription);
            }
        }
        
        // wait for all profiles to finish running
        
        for (Future<Void> activeRun : activeRuns) {
            try {
                activeRun.get();
            }
            catch (InterruptedException e) {
                logger.error("Background profile run was interrupted for test suite " + testSuite.getId(), e);
                runNotifier.fireTestFailure(new Failure(suiteDescription, e)); // fail suite
            }
            catch (ExecutionException e) {
                logger.error("Background profile run failed for test suite " + testSuite.getId(), e);
                runNotifier.fireTestFailure(new Failure(suiteDescription, e)); //fail suite
            }
        }
    }

    public TestSuite getTestSuite(String name) {
        for (TestSuite suite : testSuites) {
            if (name.equals(suite.getName())) {
                return suite;
            }
        }
        throw new RuntimeException("Cannot find a test suite for name: " + name);
    }

    public List<TestSuite> getTestSuites() {
        return testSuites;
    }

    public String getUniqueIdForTestCase(TestCase testCase, TestProfile profile) {
        return profileRunner.getUniqueIdForTestCase(testCase, profile);
    }
}
